package com.lins.store.config.schedule;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author linshuo
 * @Date 2023/1/30 15:54
 * 修改用户状态的定时任务
 */

@Slf4j
//@Component
//@EnableScheduling
public class ModifyUserStateTask implements SchedulingConfigurer {

    //用于存放任务执行周期参数
    public static String cron;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //项目部署时，会在这里执行一次，从数据库拿到cron表达式
//        cron = timerQueryMapper.getCronTime();

        //取出时间变量

        Runnable task = new Runnable() {
            @Override
            public void run() {
                //任务逻辑代码部分.
                System.out.println("I am going:" + LocalDateTime.now());
            }
        };

        //起因
        Trigger trigger = new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //任务触发，可修改任务的执行周期.
                //每一次任务触发，都会执行这里的方法一次，重新获取下一次的执行时间
//                cron = timerQueryMapper.getCronTime();
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        };
        taskRegistrar.addTriggerTask(task, trigger);

        //
    }





    //-----------Demo-----------------------------

    //    @Scheduled(cron = "0 0/1 * * * ?")
    public void testOne(){
        System.out.println("每分钟执行一次");
    }

//    @Scheduled(fixedDelay = 30000)
    public void testTwo(){
        System.out.println("每30秒执行一次");
    }

//    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行
    public void initTask(){
        //执行任务
        System.out.println("执行任务"+new Date());
    }



}
